<script setup lang="ts">
import ChatInput from './ChatInput.vue'
import { computed, nextTick, watch } from 'vue'
import { useStore } from 'vuex'

const store = useStore()
const chatUserId = computed(() => store.getters.getChatUserId)
const nickname = computed(() => store.getters.getChatNickname)
const msgId = computed(() => store.getters.getChatMsgId)
const messageList = computed(() => store.getters.getChatMessageList)

watch(
  messageList,
  () => {
    nextTick(() => {
      if (document.getElementById('msgView')) {
        document
          .getElementById('msgView')!
          .scroll(0, document.getElementById('msgView')!.scrollHeight)
      }
    })
  },
  { deep: true }
)
</script>

<template>
  <div class="flex flex-col divide-y divide-slate-200 flex-1">
    <div
      class="h-9 w-full ml-8 mb-2 text-lg flex justify-start items-center cursor-default select-none"
      style="-webkit-app-region: drag"
    >
      {{ nickname }}
    </div>

    <!-- 信息显示 -->
    <div id="msgView" class="h-full w-full overflow-y-auto" style="max-height: 450px">
      <div v-for="item in messageList" class="m-5">
        <!-- 时间、头像、消息 -->
        <div class="flex justify-center items-center text-sm mb-5 mt-5">{{ item.sendTime }}</div>
        <div v-if="item.sender === chatUserId" class="flex flex-row justify-start">
          <img class="w-10 h-10 border rounded-3xl object-scale-down" :src="item.avatar" alt="" />
          <div class="message-frame-left">
            <div class="content text-base" v-html="item.content"></div>
          </div>
        </div>

        <div v-else class="flex flex-row justify-end">
          <div class="message-frame-right">
            <div class="content" v-html="item.content"></div>
          </div>
          <img class="w-10 h-10 border rounded-3xl object-scale-down" :src="item.avatar" alt="" />
        </div>
      </div>
    </div>

    <!-- 输入框 -->
    <div class="min-h-40 max-h-96 h-40">
      <ChatInput :msg-id="msgId" :receiver="chatUserId" />
    </div>
  </div>
</template>

<style scoped>
.message-frame-left {
  text-align: left;
  max-width: 480px;
  word-wrap: break-word;
  word-break: break-all;
  overflow: hidden;
  margin: 10px;
  color: #333;
  background-color: #fff;
  border-radius: 0 10px 10px 10px;
}

.message-frame-right {
  text-align: left;
  max-width: 480px;
  word-wrap: break-word;
  word-break: break-all;
  overflow: hidden;
  margin: 10px;
  color: #333;
  background-color: #fff;
  border-radius: 10px 0 10px 10px;
}

.content {
  max-width: 448px;
  padding: 10px 8px;
}
</style>
